import { Component, OnInit } from '@angular/core';
import { Config } from '../../../service/config';
import { NzNotificationService, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { HttpServcie } from '../../../service/http.service';
import { SafeControlRecordBean } from './bean/safeControlRecordNew.bean';
import { Router } from '@angular/router';
import { element } from 'protractor';
import { LoadedRouterConfig } from '@angular/router/src/config';
import * as moment from 'moment';

@Component({
  selector: 'safe-control-record-new',
  templateUrl: './safeControlRecordNew.html',
  styleUrls: ['./safeControlRecordNew.scss']
})
export class SafeControlRecordNew implements OnInit {

  safeControlBean: SafeControlRecordBean = new SafeControlRecordBean();
  list: any = [];
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  userId: any;
  qUsedPartyId: any = null;
  total: any = 0;
  partyId: any;
  partyOtion: any = [];
  config = Config;

  timeFrom: any;    //开始时间
  timeTo: any;      //截止时间
  checkType: any;    //检查类型
  hasLawDocs: any;  //有无 httpService
  hasPunishmentDocs: any;//有无 行政处罚
  _startDate: any = null;    //开始时间 时间类型
  _endDate: any = null;      //截止时间 时间类型

  planTypeList = Config.planTypeList;

  checkItems = [
    { label: '设计', value: '1' },
    { label: '制造', value: '2' },
    { label: '安装', value: '3' },
    { label: '改造', value: '4' },
    { label: '维修', value: '5' },
    { label: '使用', value: '6' },
    { label: '气瓶充装', value: '7' },
    { label: '经营', value: '8' },
    { label: '其他', value: '9' }
  ];
  dealWays = [
    { label: '下达监察指令书', value: '1' },
    { label: '实施查封', value: '2' },
    { label: '实施扣押', value: '3' },
    { label: '其他', value: '4' }
  ];


  lawfileList: UploadFile[] = [];
  punfileList: UploadFile[] = [];
  enefileList: UploadFile[] = [];
  previewVisiblelaw = false;
  previewImagelaw = "";
  isVisible: boolean = false;
  updateData: any;
  uploadType: any;
  lawDocNos: any;
  punishmentDocNos: any;
  nzSpinning1 = false;

  constructor(
    private _notification: NzNotificationService,
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private router: Router
  ) {
    this.userId = JSON.parse(window.localStorage['user']).id;
    this.partyId = JSON.parse(window.localStorage['user']).partyId;
    let partyType = JSON.parse(window.localStorage['user']).partyType;
    if (partyType != 4) {
      this._notification.create('warning', '警告提示', '对不起，您无权限');
      this.router.navigateByUrl('/home/main');
    }
  }

  ngOnInit() {
    this.safeControlBean.pageSize = 10;
    this.safeControlBean.currentPage = 1;
    // this.query();

    this.httpServcie.queryByIdAndTypeList({ partyType: '2' }).subscribe(data => {
      if (data.status == '200') {
        let partyList = data.data;
        if (partyList && partyList.length > 0) {
          partyList.forEach(party => {
            this.partyOtion.push({
              id: party.id,
              partyName: party.partyName
            });
          });
        }
        this.httpServcie.queryByIdAndTypeList({ partyType: '1' }).subscribe(data => {
          if (data.status == '200') {
            let partyList = data.data;
            if (partyList && partyList.length > 0) {
              partyList.forEach(party => {
                this.partyOtion.push({
                  id: party.id,
                  partyName: party.partyName
                });
              });
            }
          }
        });
      }
    });

  }

  // 查询面板
  panels = {
    active: true,
    name: '查询',
    disabled: false,
    childPanel: [
      {
        active: false,
        name: '查询'
      }
    ]
  }

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(value => value.disabled || value.checked);
    const allUnChecked = this.list.every(value => value.disabled || !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => data.checked = false);
    }
  };


  //分页
  nzPageSizeChange(event) {
    this.safeControlBean.pageSize = event;
    this.safeControlBean.currentPage = 1;
    this.query();

  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.safeControlBean.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.safeControlBean.currentPage = event;
    this.query();
  }

  query() {
    let param: any = {
      checkerId: this.userId,
      currentPage: this.safeControlBean.currentPage,
      pageSize: this.safeControlBean.pageSize,
      checkType: this.checkType,
      hasLawDocs: this.hasLawDocs,
      hasPunishmentDocs: this.hasPunishmentDocs

    }
    if (this.qUsedPartyId) {
      param.usedPartyId = this.qUsedPartyId;
    }
    if (this._startDate) {
      this.timeFrom = moment(this._startDate).format("YYYYMMDDHHmmss");

    } else {
      this.timeFrom = null;
    }
    param.timeFrom = this.timeFrom;

    if (this._endDate) {
      this.timeTo = moment(this._endDate).format("YYYYMMDDHHmmss");
    } else {
      this.timeTo = null;
    }
    param.timeTo = this.timeTo;

    this.httpServcie.querySafeControlList(param).subscribe(data => {
      if (data.status == '200') {
        this.list = data.data.list;
        this.total = data.data.total;
      } else if (data.status == '401') {
        this.router.navigateByUrl('/login');
        return;
      } else {
        // 异常
        this._notification.create('error', '错误提示', data.message);
      }

    });
  }

  toExport(id) {
    this.httpServcie.exportSafeControl(id).subscribe(data => {
      this.download(data.data.fileUrl, data.data.fileName);
    });
  }
  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }


  //打开上传模态框
  uploadwenj(data, type) {
    this.lawfileList = [];
    this.punfileList = [];
    this.enefileList = [];
    this.updateData = data;
    this.isVisible = true;
    this.uploadType = type;
    if (type == 1) {
      this.lawDocNos = data.lawDocNos;
      if (data.lawDocs) {
        (data.lawDocs + "").split(',').forEach(ele => {
          let noew = new Date().getTime();
          let file: UploadFile = {
            "thumbUrl": this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.lawfileList.push(file);
        })
      }
    }
    if (type == 2) {
      this.punishmentDocNos = data.punishmentDocNos;
      if (data.punishmentDocs) {
        (data.punishmentDocs + "").split(',').forEach(ele => {
          let noew = new Date().getTime();
          let file: UploadFile = {
            "thumbUrl": this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231,
            name: ele,
            type: 'image/png',
            response: {
              data: ele
            }
          }
          this.punfileList.push(file);
        })
      }
    }

    if (type == 3) {
      if (data.evidences) {
        (data.evidences + "").split(',').forEach(ele => {
          let noew = new Date().getTime();
          let file: UploadFile = {
            thumbUrl: this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.enefileList.push(file);
        })
      }
    }
  }

  //上传文件完成后的回调
  nzChangelaw(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    if (event.file.status == "done") {
      if (this.uploadType == 1) {
        this.lawfileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }
      if (this.uploadType == 2) {
        this.punfileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

    }
  }

  //预览的查看
  handlePreviewlaw = (file: UploadFile) => {
    this.previewImagelaw =
      this.config.IP + this.config.API.getUpload + file["response"]["data"] ||
      file.thumbUrl;
    this.previewVisiblelaw = true;
  };

  //删除文件
  nzRemoveFilelaw = (file: UploadFile) => {
    this.httpServcie.deleteUpload(file["response"]["data"]).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }

        if(data["status"] == "200"){
          this._notification.create("success", "成功提示", "删除成功，请点击确定按钮，进行数据保存！");
        }else{
          this._notification.create("error", "错误提示", data.message);
        }

        if (this.uploadType == 1) {
          if (this.lawfileList.length == 1) {
            this.lawfileList = [];
            return;
          }
          this.lawfileList.forEach((element, index) => {
            if (element["status"] == "removed") {
              this.lawfileList.splice(index, 1);
            }
          });
        }
        /*行政处罚书*/
        if (this.uploadType == 2) {
          if (this.punfileList.length == 1) {
            this.punfileList = [];
            return;
          }
          this.punfileList.forEach((element, index) => {
            if (element["status"] == "removed") {
              this.punfileList.splice(index, 1);
            }
          });
        }

        /*检查存证*/
        if (this.uploadType == 3) {
          if (this.enefileList.length == 1) {
            this.enefileList = [];
            return;
          }
          this.enefileList.forEach((element, index) => {
            if (element["status"] == "removed") {
              this.enefileList.splice(index, 1);
            }
          });
        }
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  };


  //上传完了之后 提交数据
  update() {
    // 更新执法文书
    if (this.uploadType == 1) {
      let param = {
        id: this.updateData.id,
        lawDocNos: this.lawDocNos,
        lawDocs: null
      }
      let list = [];
      this.lawfileList.forEach(element => {
        list.push(element.response.data);
      });
      param.lawDocs = list.join(',');
      this.httpServcie.updateSafeLawDoc(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.lawDocNos = null;
          this.lawfileList = [];
          this.query();
        }
      });
    }
    // 更新行政处罚书
    if (this.uploadType == 2) {
      let param = {
        id: this.updateData.id,
        punishmentDocNos: this.punishmentDocNos,
        punishmentDocs: null
      }
      let list = [];
      this.punfileList.forEach(element => {
        list.push(element.response.data);
      });
      param.punishmentDocs = list.join(',');
      this.httpServcie.updateSafePunDoc(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.punishmentDocNos = null;
          this.punfileList = [];
          this.query();
        }
      });
    }
    // 更新检查存证
    if (this.uploadType == 3) {
      let param = {
        id: this.updateData.id,
        evidences: null
      }
      let list = [];
      this.enefileList.forEach(element => {
        list.push(element.response.data);
      });
      param.evidences = list.join(',');
      this.httpServcie.updateSafeEvidences(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.enefileList = [];
          this.query();
        }
      });
    }

  }

  beforeUpload = (file: File) => {
    this.nzSpinning1 = true;
    return true;
  };

  //上传回调
  uploadChage(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    this.nzSpinning1 = false;
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "上传成功");
      }
      // Get this url from response in real world.
    }
  }

  downloadwenj(data, type) {
    //检查记录
    if (type == 1) {
      // this.httpServcie.exportSafeControl(data.id).subscribe(data => {
      //   this.download(data.data.fileUrl, data.data.fileName);
      // });
      if(!data.inspectionRecordsDoc){
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.inspectionRecordsDoc.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '监督检查记录附件' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    //执法文书
    if (type == 2) {
      if (!data.lawDocs) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.lawDocs.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '执法文书附件' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }

    }
    //行政处罚书
    if (type == 3) {
      if (!data.punishmentDocs) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.punishmentDocs.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '行政处罚书附件' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    //证据
    if (type == 4) {
      if (!data.evidences) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.evidences.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '检查存证记录' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    // 委托检测报告
    if (type == 5) {
      if (!data.entrustChedName) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.entrustChedName.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '委托检测报告' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
  }

  newArray = len => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  };
  _startValueChange = () => {
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  };
  _endValueChange = () => {
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  };
  _disabledStartDate = startValue => {
    if (!startValue || !this._endDate) {
      return false;
    }
    return startValue.getTime() >= this._endDate.getTime();
  };
  _disabledEndDate = endValue => {
    if (!endValue || !this._startDate) {
      return false;
    }
    return endValue.getTime() <= this._startDate.getTime();
  };
  get _isSameDay() {
    return (
      this._startDate &&
      this._endDate &&
      moment(this._startDate).isSame(this._endDate, "day")
    );
  }
  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this._startDate.getHours()) : [];
      },
      nzDisabledMinutes: h => {
        if (this._isSameDay && h === this._startDate.getHours()) {
          return this.newArray(this._startDate.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (
          this._isSameDay &&
          h === this._startDate.getHours() &&
          m === this._startDate.getMinutes()
        ) {
          return this.newArray(this._startDate.getSeconds());
        }
        return [];
      }
    };
  }

}
